import json
from urllib import request,parse

# from App_ReadNovel.models import UserisNice, collection
from App_SearchNovel.models import Books


def TranslateTool(keyword):
    base_url = 'https://fanyi.baidu.com/sug'

    # 构建请求对象
    data = {
        'kw': keyword.strip()
    }
    data = parse.urlencode(data)

    # 模拟浏览器
    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"}

    req = request.Request(url=base_url, data=bytes(data, encoding='utf-8'), headers=header)
    res = request.urlopen(req)

    # 获取响应的json字符串
    str_json = res.read().decode('utf-8')
    # 把json转换成字典
    myjson = json.loads(str_json)
    info = myjson['data'][0]['v']
    return info

def iscollection(userid,bookid):
    try:
        Books.objects.get(bookid=bookid).iscollection.get(userid=userid)
        return True
    except:
        return False



def isnice(userid, bookid):
    try:
        book = Books.objects.get(bookid=bookid)
        book.isnice.get(userid=userid)
        return True
    except:
        return False